package com.hepinghospital.user.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.gyf.immersionbar.ImmersionBar;
import com.hepinghospital.user.R;
import com.hepinghospital.user.service.WebSocketService;
import com.hepinghospital.user.ui.kotlin.WelcomeActivity;
import com.hepinghospital.user.ui.widget.LoadingDailog;
import com.hepinghospital.user.util.DisplayUtil;
import com.rest.client.RestClient;

import java.util.ArrayList;

import butterknife.ButterKnife;
import jz.joyoung.robot.util.NetworkUtil;
import jz.joyoung.robot.util.UtilString;


public abstract class BaseActivity extends AppCompatActivity {

    public ImageView btn_back;

    public boolean flag = false;
    protected String TAG;


    protected Activity mContext;

    private LoadingDailog loadingDailog;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        TouchEffectsFactory.initTouchEffects(this);
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //为了防止重复启动多个闪屏页面
            finish();
            return;

        }
        if (savedInstanceState != null) {
            int currentPID = android.os.Process.myPid();
            if (currentPID != savedInstanceState.getInt("PID")) {
                startActivity(WelcomeActivity.class);
                finish();
            }
        }
        TAG = getClass().getSimpleName();
        mContext = this;
        doBeforeSetcontentView();
        setContentView(getLayoutResource());
        ButterKnife.bind(this);
        initBack();
        initData();
        initViews();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("PID", android.os.Process.myPid());
    }

    public void initBack() {
        btn_back = findViewById(R.id.btn_back);
        if (btn_back != null) {
            btn_back.setOnClickListener(v -> finish());
        }
    }

    /**
     * 设置layout前配置
     */
    protected void doBeforeSetcontentView() {
        ImmersionBar.with(this).keyboardEnable(true).fitsSystemWindows(true).statusBarColor(R.color.white).statusBarDarkFont(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }


    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //我看可以重启服务，如果服务断了
        checkServiceRunning(mContext);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }


    //是否触摸在指定view上面,对某个控件过滤
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
//            return true;
//        }
//        lastClickTime = System.currentTimeMillis();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) {
                return super.dispatchTouchEvent(ev);
            }
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
                return super.dispatchTouchEvent(ev);
            }
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                //隐藏键盘
//                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);

    }


    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }

    protected abstract void initViews();

    protected abstract void initData();

    protected abstract int getLayoutResource();


    /**
     * 防止闪屏加载框
     *
     * @param activity
     */
    public void showLoadingDialog(Activity activity) {
        if (NetworkUtil.isNetworkAvailable(this)) {
            if (activity != null) {
                LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                        .setMessage("加载中...")
                        .setCancelable(true)
                        .setCancelOutside(false);
                loadingDailog = loadBuilder.create();
                loadingDailog.showDialog();
            }
        }
    }

    public void dismissLoadingDialog() {
        if (loadingDailog != null) {
            loadingDailog.hideDialog();
        }
    }


    /**
     * 打开设置权限页面
     */
    @SuppressLint("ObsoleteSdkInt")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void startNotificationSetting(Context context) {
        try {
            Intent mIntent = new Intent();
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
            context.startActivity(mIntent);

        } catch (Exception ignored) {

        }
    }

    // 检查服务重新连接
    public void checkServiceRunning(Context context) {
        if (!UtilString.isEmpty(RestClient.getInstance().token) && !UtilString.isEmpty(BaseApplication.currentUserId)) {
            if (!isServiceRunning(mContext, "com.hepinghospital.user.service.WebSocketService")) {
                Log.e("基类服务死了---", "妈的");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(mContext, WebSocketService.class));
                } else {
                    startService(new Intent(mContext, WebSocketService.class));
                }
            } else {
                Log.e("基类服务还在---", "哈哈哈");
            }
        } else {
            stopService(new Intent(mContext, WebSocketService.class));
        }
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) am.getRunningServices(Integer.MAX_VALUE);

        for (ActivityManager.RunningServiceInfo info : runningService) {// 获取运行服务再启动
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        return DisplayUtil.getResources(this, resources, 1f);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(DisplayUtil.attachBaseContext(base, 1f));
    }
}